package models.admin;

import models.UUIDModel;
import models.campus.Campus;
import models.constants.DeletedStatus;
import play.db.jpa.JPA;
import util.common.UStringUtil;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.List;

/**
 * 员工物业/园区管理
 * Created by youliangcheng on 17/2/10.
 */
@Entity
@Table(name = "admin_user_campus")
public class AdminUserCampus  extends UUIDModel {

    @ManyToOne
    @JoinColumn(name = "admin_user_id")
    public AdminUser adminUser;

    /**
     * 物业/园区
     */
    @ManyToOne
    @JoinColumn(name = "campus_id")
    public Campus campus;


    /**
     * 删除
     * @param ids
     */
    public static void deleteByIds(String[] ids){
        String idStr = "'"+UStringUtil.concatStr("','",ids)+"'";
        String  sqlUpdate = " update admin_user_campus a set a.deleted = 1 where a.id in ("+idStr+")";
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }

    /**
     * 根据AdminUser Id 查询员工管理的园区/物业
     * @param id
     * @return
     */
    public static List<AdminUserCampus> loadByUserId(long id){
        return AdminUserCampus.find("adminUser.id = ? and deleted = ?",id , DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 用户所管辖的所有物业id
     * @param adminUserId
     * @return
     */
    public static String getCampusIdByAdminUser(long  adminUserId){
        String idStr = "";
        List<AdminUserCampus> adminUserCampusList = AdminUserCampus.find(" deleted = ? and adminUser.id = ?" ,DeletedStatus.UN_DELETED ,adminUserId).fetch();
        if(adminUserCampusList!= null && adminUserCampusList.size() >0){
            for(AdminUserCampus adminUserCampus : adminUserCampusList){
                idStr += ",'"+adminUserCampus.campus.getId()+"'";
            }
        }
        return idStr.length() > 0 ? idStr.substring(1) :idStr;
    }

    /**
     * 根据物业查询相关联的维护人员
     * @param campusId
     * @return
     */
    public static String getAdminUserByCampuse(String campusId){
        String idStr = "";
        List<AdminUserCampus> adminUserCampusList = AdminUserCampus.find(" deleted = ? and campus.id = ?" ,DeletedStatus.UN_DELETED ,campusId).fetch();

        if(adminUserCampusList!= null && adminUserCampusList.size() >0){
            for(AdminUserCampus adminUserCampus : adminUserCampusList){
                idStr += ","+adminUserCampus.adminUser.id;
            }
        }
        return idStr.length() > 0 ? idStr.substring(1) :idStr;
    }
}
